package com.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.dto.ApiResponse;
import com.example.dto.GenerateResetTokenRequest;
import com.example.dto.ResetPasswordRequest;
import com.example.dto.TokenResponse;
import com.example.service.UserService;

import jakarta.validation.Valid;

@RestController
@RequestMapping("/api/password")
public class PasswordResetController {

    @Autowired
    private UserService userService;
    /**
     * 生成重置密码令牌
     * 该接口用于管理员为用户生成重置密码的令牌。
     *
     * @param request 包含用户名信息的请求体，用于指定需要生成重置令牌的用户
     * @return 如果用户存在，返回包含重置令牌的响应；如果用户不存在，返回错误响应
     */
    @PostMapping("/generate-reset-token")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> generateResetToken(@Valid @RequestBody GenerateResetTokenRequest request) {
        TokenResponse token = userService.generateResetToken(request.getUsername());
        if (token == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error("User not found"));
        }
        return ResponseEntity.ok(ApiResponse.success("Reset token generated successfully", token));
    }
    /**
     * 重置用户密码接口
     * 该接口用于处理用户密码重置请求，接收包含新密码的请求体，并调用服务层进行密码重置操作。
     *
     * @param request 包含新密码的请求体，类型为ResetPasswordRequest
     * @return 如果密码重置成功，则返回成功的响应；否则返回错误的响应
     */
    @PostMapping("/reset")
    public ResponseEntity<?> resetPassword(@Valid @RequestBody ResetPasswordRequest request) {
        ApiResponse<?> response = userService.resetPassword(request);
        if (response.isSuccess()) {
            return ResponseEntity.ok(response);
        } else {
            return ResponseEntity.badRequest().body(response);
        }
    }
}